package com.mti.zhpt.controller;

import com.github.pagehelper.PageInfo;
import com.mti.zhpt.model.EventEntity;
import com.mti.zhpt.model.EventQueryPram;
import com.mti.zhpt.model.EventTimerEntity;
import com.mti.zhpt.service.impl.AddressServiceImpl;
import com.mti.zhpt.service.impl.EventDetailsServiceImpl;
import com.mti.zhpt.service.impl.EventServiceImpl;
import com.mti.zhpt.shared.core.ret.RetResponse;
import com.mti.zhpt.shared.core.ret.RetResult;
import com.mti.zhpt.shared.utils.StringUtil;
import com.mti.zhpt.utils.DateUtil;
import com.mti.zhpt.vo.EventRequestDTO;
import com.mti.zhpt.vo.PageDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 案事件 zhaopf@mti-sh.cn 2019年4月18日10:51
 */
@RestController
@RequestMapping(path = "/event")
@Api(value = "/event", tags = { "案情事件" })
@Slf4j
public class EventController {

	@Autowired
	private EventServiceImpl eventService;
	@Autowired
	private EventDetailsServiceImpl eventDetailsService;
	@Autowired
	private AddressServiceImpl addressService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class,
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false));
	}

	@RequestMapping(path = "/list", method = RequestMethod.POST)
	@Deprecated
	@ApiOperation(value = "根据时间、案件类型、查询案件集合")
	public RetResult<List<Map<String, Object>>> query(@RequestBody EventEntity entity) {
		List<Map<String, Object>> result = null;
		try {
			result = eventService.queryList(entity);
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());

		}
		return RetResponse.makeOKCp(result);
	}

	@RequestMapping(path = "/listByPrams", method = RequestMethod.POST)
	@ApiOperation(value = "根据时间、案件类型查询案件集合")
	public RetResult<List<Map<String, Object>>> listByPrams(@RequestBody EventQueryPram eventQueryPram) {
		List<Map<String, Object>> result = null;
		try {
			result = eventService.listByPrams(eventQueryPram);
		} catch (Exception e) {
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp(result);
	}

    /**
     * 添加新案件
     *
     * @param event 案件对象
     * @return
     */
	@RequestMapping(path = "/addEventByEventEntity", method = RequestMethod.POST)
	@ApiOperation(value = "添加新案件")
	public RetResult<EventEntity> addEventByEventEntity(@RequestBody() EventEntity event) {
		try {
			if (event.getLongitude() == 0 || event.getLatitude() == 0) {
				List<Map<String, Object>> addresslist = addressService.getLonLat("%" + event.getAddress() + "%");
				Map<String, Object> thisaddress = addresslist.get(0);
				event.setLongitude((Double) thisaddress.get("longitude"));
				event.setLatitude((Double) thisaddress.get("latitude"));
			}
			eventService.addEventByEventEntity(event);
		} catch (Exception e) {
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp(event);
	}

	@RequestMapping(path = "/delEventNewCreated", method = RequestMethod.GET)
	@Deprecated
	@ApiOperation(value = "一键清除新添加的案件(内部接口)--注意，会清除所有EVENTID>=10的案件，因为默认的初始化案件EVENTID<10")
	public RetResult<Object> delEventNewCreated(
			@ApiParam(required = false, name = "mineventId", value = "会删除所有大于该案件ID的案件", example = "6") @RequestParam(value = "mineventId", required = false,defaultValue = "6") String mineventId) {
		try {
			eventService.delEventNewCreated(mineventId);
		} catch (Exception e) {
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp();
	}

	@RequestMapping(path = "/updateEventStatus", method = RequestMethod.GET)
	@ApiOperation(value = "更新案件状态")
	public RetResult<Integer> updateEventStatus(
			@ApiParam(required = true, name = "eventId", value = "案件ID", example = "6") @RequestParam(value = "eventId", required = true) String eventId,
			@ApiParam(required = true, name = "status", value = "案件状态0-3[0:待处置,1:处置中,2:处置完成,3:被退回]", example = "1") @RequestParam(value = "status", required = true) Integer status) {
		int result = 0;
		try {
			result = eventService.updateEventStatus(eventId, status);
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp(result);
	}

	@RequestMapping(path = "/updateSendTime", method = RequestMethod.GET)
	@ApiOperation(value = "案件下发")
	public RetResult<Integer> updateSendTime(
			@ApiParam(required = true, name = "eventId", value = "案件ID", example = "6") @RequestParam(value = "eventId", required = true) String eventId,
			@ApiParam(required = true, name = "sendTime", value = "下发时间", example = "2019-05-01 12:33:34") @RequestParam(value = "sendTime", required = true) String sendTime) {
		int result = 0;
		try {
			result = eventService.updateSendTime(eventId, DateUtil.strToDate(sendTime, DateUtil.datetimeFormat));
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp(result);
	}

	@RequestMapping(path = "/query-details", method = RequestMethod.GET)
	@ApiOperation(value = "根据event_id、查找事件信息、时间轴")
	public RetResult<Map<Object, Object>> queryDetails(
			@ApiParam(required = true, name = "eventId", value = "案件ID", example = "6") @RequestParam(value = "eventId", required = true) String eventId) {
		Map<Object, Object> result = null;
		try {
			result = eventDetailsService.queryDetails(eventId);
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());

		}

		return RetResponse.makeOKCp(result);
	}

	@RequestMapping(path = "/queryNearBy", method = RequestMethod.GET)
	@ApiOperation(value = "根据event_id、距离搜索周边资源" +
			"Events ：事件" +
			"Polices 警力：status 1 警车 2 民警" +
			"Companys 单位 : kind 1 医院  2 消防 3 学校 4 重点单位 5 企事业单位" +
			"Trafficcheckpoints ：卡口检查站" +
			"Moniters 监控: " +
			"卡口监控：kind 人脸：407（在线）408（离线） 车辆：405(在线) 406（离线）\n" +
			"枪型监控：kind 257(在线) 401（离线）\n" +
			"球型监控：kind 402（在线） 403（离线）\n")
	public RetResult<Map<String, Object>> queryNearBy(
			@ApiParam(required = true, name = "eventId", value = "案件ID", example = "6") @RequestParam(value = "eventId", required = true) String eventId,
			@ApiParam(required = true, name = "dis", value = "搜索范围(米)", example = "10000") @RequestParam(value = "dis", required = true) Integer dis,
			@ApiParam(required = false, name = "orderbydis", value = "是否按照距离排序", example = "true") @RequestParam(value = "orderbydis", required = false, defaultValue = "true") boolean orderbydis) {

		Map<String, Object> result = null;
		try {
			result = eventService.queryNearBy(eventId, (int) (dis * 0.8), orderbydis);
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp(result);
	}
	@RequestMapping(path = "/queryNearByType", method = RequestMethod.GET)
	@ApiOperation(value = "根据event_id、距离搜索周边资源")
	public RetResult<Map<String, Object>> queryNearByEvents(
			@ApiParam(required = true, name = "eventId", value = "案件ID", example = "6") @RequestParam(value = "eventId", required = true) String eventId,
			@ApiParam(required = true, name = "dis", value = "搜索范围(米)", example = "10000") @RequestParam(value = "dis", required = true) Integer dis,
			@ApiParam(required = false, name = "orderbydis", value = "是否按照距离排序", example = "true") @RequestParam(value = "orderbydis", required = false, defaultValue = "true") boolean orderbydis,
			@ApiParam(required = false, name = "type", value = "类型: 事件 Events 辖区 Jurisdictions 警力 Polices 监控 Moniters 卡口检查站 Trafficcheckpoints 单位 Companys", example = "Events") @RequestParam(value = "type", required = false, defaultValue = "") String type) {

		Map<String, Object> result = null;
		try {
			result = eventService.queryNearByType(eventId, (int) (dis * 0.8), orderbydis, type);
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp(result);
	}

	@RequestMapping(path = "/queryNearByPolices", method = RequestMethod.GET)
	@ApiOperation(value = "根据event_id、距离搜索周边警员并排序" +
			"Polices 警力：status 1 警车 2 民警\" +")
	public RetResult<Map<String, Object>> queryNearByPolices(@ApiParam(required = true, name = "eventId", value = "案件ID", example = "6") @RequestParam(value = "eventId", required = true) String eventId,
			@ApiParam(required = true, name = "dis", value = "搜索范围(米)", example = "10000") @RequestParam(value = "dis", required = true) Integer dis,
			@ApiParam(required = false, name = "orderbydis", value = "是否按照距离排序", example = "true") @RequestParam(value = "orderbydis", required = false, defaultValue = "true") boolean orderbydis) {

		Map<String, Object> result = null;
		try {
			result = eventService.queryNearByPolices(eventId, (int) (dis * 0.8), orderbydis);
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp(result);
	}
	
	@RequestMapping(path = "/pushEventNewCreated", method = RequestMethod.GET)
	@Deprecated
	@ApiOperation(value = "推送案事件(演示用的内部接口)")
	public RetResult<Object> pushEventNewCreated() {
		try {
			eventService.pushEventNewCreated();
		} catch (Exception e) {
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp();
	}

	@RequestMapping(path = "/pageByEvent", method = RequestMethod.POST)
	@ApiOperation(value = "根据案件对象分页查询案件集合(警情列表)")
	public RetResult pageByEvent(@RequestBody EventEntity event) {
		PageInfo result = null;
		try {
			result = eventService.pageByEvent(event);
			return RetResponse.makeOKCp(result);
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());

		}
	}

	@RequestMapping(path = "/listByEvent", method = RequestMethod.POST)
	@ApiOperation(value = "根据时间查询案件event_id, longitude,latitude,level")
	public RetResult<List<Map<String, Object>>> listByEvent(@RequestBody EventEntity entity) {
		List<Map<String, Object>> result = null;
		try {
			result = eventService.listByEvent(entity);
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());

		}
		return RetResponse.makeOKCp(result);
	}

	/**
	 * 日常警情升级为重大警情
	 *
	 * @param entity 警情对象
	 * @return
	 */
	@RequestMapping(path = "/upgradeImportEvent", method = RequestMethod.POST)
	@ApiOperation(value = "日常警情升级为重大警情")
	public RetResult upgradeImportEvent(@RequestBody EventEntity entity) {
		Boolean result;
		try {
			result = eventService.upgradeImportEvent(entity);
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp(result);
	}

	/**
	 * 警情反馈补充
	 *
	 * @param eventTimerEntity 时间轴对象
	 * @return
	 */
	@RequestMapping(path = "/insertEventTimer", method = RequestMethod.POST)
	@ApiOperation(value = "警情反馈补充")
	public RetResult insertEventTimer(@RequestBody EventTimerEntity eventTimerEntity) {
		Boolean result;
		try {
			result = eventService.insertEventTimer(eventTimerEntity);
		} catch (Exception e) {
			log.error(e.getMessage());
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp(result);
	}

	/**
	 * 快速处置
	 *
	 * @param event 案件对象
	 * @return
	 */
	@RequestMapping(path = "/fastDetail", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ApiOperation(value = "快速处置")
	public RetResult<EventEntity> fastDetail(@RequestBody() EventEntity event) {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes)ra;
		HttpServletRequest request = sra.getRequest();
		String token = request.getHeader("Authorization");
		if (StringUtil.isEmpty(token)) {
			return RetResponse.makeErrCp("非法请求，未登录或登录超时");
		}
		try {
			eventService.fastDetail(token, event);
		} catch (Exception e) {
			return RetResponse.makeErrCp(e.getMessage());
		}
		return RetResponse.makeOKCp(event);
	}

//	@PostMapping(value = "/list/pageV0")
//	@ApiOperation(value = "警情列表接口V0")
//	public RetResult<PageDTO> getListPageV0(@RequestBody EventRequestDTO dto){
//		return RetResponse.makeOKCp(eventService.listByPage(dto));
//	}
//
//	@PostMapping(value = "/list/pageV2")
//	@ApiOperation(value = "警情列表接口V2")
//	public RetResult<PageDTO> getListPageV2(@RequestBody EventRequestDTO dto){
//		return RetResponse.makeOKCp(eventService.listByPageV2(dto));
//	}

	@PostMapping(value = "/list/page")
	@ApiOperation(value = "警情列表接口")
	public RetResult<PageDTO> getListPage(@RequestBody EventRequestDTO dto){
		return RetResponse.makeOKCp(eventService.listByPageV3(dto));
	}
}
